import {
  ArgumentsHost,
  Catch,
  ExceptionFilter,
  HttpException,
  HttpStatus,
} from '@nestjs/common';
import { Response } from 'express';

@Catch()
export class AllExceptionsFilter implements ExceptionFilter {
  catch(exception: unknown, host: ArgumentsHost): void {
    const ctx = host.switchToHttp();
    const response = ctx.getResponse<Response>();
    const status =
      exception instanceof HttpException
        ? exception.getStatus()
        : HttpStatus.INTERNAL_SERVER_ERROR;
    let message = '';
    if (exception['response'] && exception['response']['message']) {
      message = exception['response']['message'];
      if (Array.isArray(message)) {
        message = message[0];
      }
    } else {
      message = exception['message'];
    }
    console.log('全局异常信息:', message, exception['stack']);
    response.status(status).json({
      success: false,
      code: status,
      message,
    });
  }
}
